//
//  XS_RechargeVC.swift
//  XueDao
//
//  Created by Mac on 2020/12/31.
//

import UIKit
import SwiftyStoreKit
import StoreKit
import HandyJSON

class XS_RechargeVC: XS_BaseVC {

    @IBOutlet weak var collectionView: UICollectionView!
    @IBOutlet weak var accountLabel: UILabel!
    @IBOutlet weak var confirmBtn: UIButton!
    @IBOutlet weak var contentLab: UILabel!
    
    var result : [SKProduct] = []
    var selectProduct : SKProduct?
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        collectionView.register(UINib.init(nibName: "XS_RechargeItemCell", bundle: Bundle.main), forCellWithReuseIdentifier: "XS_RechargeItemCell")
        
        if XS_Singleton.shared.infoModel?.userBO != nil {
            let accountAttStr = NSMutableAttributedString.init(string: "￥\(XS_Singleton.shared.infoModel?.userBO.money ?? "")")
            accountAttStr.addAttributes([.font : UIFont.systemFont(ofSize: 16, weight: .medium)], range: NSRange.init(location: 0, length: 1))
            accountLabel.attributedText = accountAttStr
        } else {
            accountLabel.text = ""
            accountLabel.attributedText = nil
        }
        
        contentLab.text = "1、学到币可用于直接购买APP虚拟内容（不含实物产品，线下课，会员连续包月）\n\n2、IOS 系统和其他系统的学到币只能在相应系统使用，不能互通使用\n\n3、学到币为虚拟币，充值后学到币不会过期，但是无法提现或转赠他人"
        
        confirmBtn.isEnabled = false
        confirmBtn.backgroundColor = UIColor.lightGray.withAlphaComponent(0.5)
        requestData()
    }
    
    func requestData(){
        let point = CGPoint(x: .screenWidth/2.0, y: .screenHeight/2.0 - .scale*150)
        view.isUserInteractionEnabled = false
        view.makeToastActivity(point)
        SwiftyStoreKit.retrieveProductsInfo(["com.xuedao.xuedaoonline6","com.xuedao.xuedaoonline68","com.xuedao.xuedaoonline88","com.xuedao.xuedaoonline208","com.xuedao.xuedaoonline388","com.xuedao.xuedaoonline998"]) { result in
            let newResults = result.retrievedProducts.sorted { (firstProduct, secondProduct) -> Bool in
                if firstProduct.price.intValue < secondProduct.price.intValue{
                    return true
                }
                return false
            }
            self.view.isUserInteractionEnabled = true
            self.view.hideToastActivity()
            self.result = newResults
            self.collectionView.reloadData()
        }
    }
    
    @IBAction func confirmBtnAction(_ sender: UIButton) {
        let point = CGPoint(x: .screenWidth/2.0, y: .screenHeight/2.0 - .scale*150)
        view.isUserInteractionEnabled = false
        view.makeToastActivity(point)
        SwiftyStoreKit.purchaseProduct(selectProduct!) { (result) in
            switch result {
            case .success (let purchase):
                if purchase.needsFinishTransaction{
                    SwiftyStoreKit.finishTransaction(purchase.transaction)
                }
                let receiptData = SwiftyStoreKit.localReceiptData
                let receiptString = receiptData?.base64EncodedString(options: [])
                let priceStr = String.init(format: "%@", purchase.product.price)
                XS_NetWork.requestJson("/money/rechargeMoneyIOS", parameters: ["payMoney":priceStr,"money":priceStr,"transactionId":purchase.transaction.transactionIdentifier ?? "","payload":receiptString ?? ""])
                    .subscribe(onNext: { resp in //直接返回原始数据 resp.data
                        self.view.isUserInteractionEnabled = true
                        self.view.hideToastActivity()
                        DispatchQueue.main.async {
                            if resp.success{
                                let currentMoney = (Int(XS_Singleton.shared.infoModel?.userBO.money ?? "0") ?? 0) + purchase.product.price.intValue
                                XS_Singleton.shared.infoModel?.userBO.money = String.init(format: "%ld", currentMoney)
                                self.accountLabel.text = String.init(format: "%ld", currentMoney as CVarArg)
                            }
                            else{
                                self.view.makeToast(resp.msg)
                            }
                            
                        }
                    })
            case .error (let error):
                self.view.isUserInteractionEnabled = true
                self.view.hideToastActivity()
                self.view.makeToast(error.localizedDescription)
                break
            }
        }
    }
    
}

extension XS_RechargeVC : UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout{
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return result.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "XS_RechargeItemCell", for: indexPath) as! XS_RechargeItemCell
        if indexPath.item < result.count {
            cell.model = result[indexPath.item]
        }
        return cell
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize.init(width: floor((.screenWidth - 48) / 3), height: 72)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 16
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 8
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets.init(top: 8, left: 16, bottom: 32, right: 16)
    }
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath) as! XS_RechargeItemCell
        selectProduct = cell.model
        cell.contentView.layer.borderColor = UIColor(red: 0.93, green: 0.40, blue: 0.25, alpha: 1.00).cgColor
        cell.contentView.layer.borderWidth = 1
        confirmBtn.isEnabled = true
        confirmBtn.backgroundColor = UIColor(red: 0.93, green: 0.40, blue: 0.25, alpha: 1.00)
    }
    
    func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
        let cell = collectionView.cellForItem(at: indexPath)
        cell?.contentView.layer.borderColor = UIColor(red: 0.93, green: 0.40, blue: 0.25, alpha: 1.00).cgColor
        cell?.contentView.layer.borderWidth = 0
        confirmBtn.isEnabled = true
        confirmBtn.backgroundColor = UIColor(red: 0.93, green: 0.40, blue: 0.25, alpha: 1.00)
    }
}
